﻿using System;

using Kingdee.BOS;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.WebApi.FormService;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Hamster.K3Cloud.WebAPI.ServerExtend
{
    /// <summary>
    /// 单据处理
    /// </summary>
    public class BillHandler
    {
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static Result Delete(Context context, Parameter parameter)
        {
            Result result = new Result();
            var rs = WebApiServiceCall.Delete(context, parameter.NextFormId, Formater.Delete(parameter));
            ResponseData res = Formater.ConvertWebAPIResult(rs);
            if (!res.Result.ResponseStatus.IsSuccess)
            {
                result.msg = JsonConvert.SerializeObject(res.Result.ResponseStatus.Errors);
                return result;
            }

            result.success = true;
            result.msg = Defineds.DefaultSuccessMsg;
            return result;
        }

        /// <summary>
        /// 保存和更新
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static Result Save(Context context, Parameter parameter)
        {
            Result result = new Result();
            string strParameter = "";
            if (parameter.Model.Property("FID") != null && Convert.ToInt64(parameter.Model["FID"]) > 0)
            {
                strParameter = Formater.Create(parameter);
            } 
            else
            {
                strParameter = Formater.Update(parameter);
            }

            var rs = WebApiServiceCall.Save(context, parameter.NextFormId, strParameter);
            ResponseData res = Formater.ConvertWebAPIResult(rs);
            if (!res.Result.ResponseStatus.IsSuccess)
            {
                result.msg = JsonConvert.SerializeObject(res.Result.ResponseStatus.Errors);
                return result;
            }

            result.data = new JObject
            {
                new JProperty("FID", res.Result.ID),
                new JProperty("Number", res.Result.Number)
            };

            // TODO 需要处理提交和审核不成功之后，单据的处理
            // 当前需要客户端接收单据ID和单据编号，再次请求进行更新
            // 是否需要提交和审核
            if (parameter.IsAutoSubmitAndAudit)
            {
                // 提交
                if (parameter.Model.Property("FID") == null && Convert.ToInt64(parameter.Model["FID"]) == 0)
                {
                    parameter.Model.Add(new JProperty("FID", res.Result.ID));
                }

                if (parameter.Model.Property("FBillNo") == null && Convert.ToInt64(parameter.Model["FBillNo"]) == 0)
                {
                    parameter.Model.Add(new JProperty("FBillNo", res.Result.Number));
                }

                var rsSubmit = WebApiServiceCall.Submit(context, parameter.NextFormId, Formater.Submit(parameter));
                ResponseData rsSubmitData = Formater.ConvertWebAPIResult(rsSubmit);
                if (!rsSubmitData.Result.ResponseStatus.IsSuccess)
                {
                    // 删除单据

                    result.success = false;
                    result.msg = JsonConvert.SerializeObject(rsSubmitData.Result.ResponseStatus.Errors);
                    return result;
                }

                // 审核
                var rsAudit = WebApiServiceCall.Audit(context, parameter.NextFormId, Formater.Audit(parameter));
                ResponseData rsAuditData = Formater.ConvertWebAPIResult(rsAudit);
                if (!rsAuditData.Result.ResponseStatus.IsSuccess)
                {
                    result.success = false;
                    result.msg = JsonConvert.SerializeObject(rsAuditData.Result.ResponseStatus.Errors);
                    return result;
                }
            }

            result.msg = Defineds.DefaultSuccessMsg;
            return result;
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static Result Audit(Context context, Parameter parameter)
        {
            Result result = new Result();
            var rs = WebApiServiceCall.Audit(context, parameter.NextFormId, Formater.Audit(parameter));
            ResponseData res = Formater.ConvertWebAPIResult(rs);
            if (!res.Result.ResponseStatus.IsSuccess)
            {
                result.msg = JsonConvert.SerializeObject(res.Result.ResponseStatus.Errors);
                return result;
            }

            result.success = true;
            result.msg = Defineds.DefaultSuccessMsg;
            return result;
        }

        /// <summary>
        /// 反审核
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static Result UnAudit(Context context, Parameter parameter)
        {
            Result result = new Result();
            var rs = WebApiServiceCall.UnAudit(context, parameter.NextFormId, Formater.UnAudit(parameter));
            ResponseData res = Formater.ConvertWebAPIResult(rs);
            if (!res.Result.ResponseStatus.IsSuccess)
            {
                result.msg = JsonConvert.SerializeObject(res.Result.ResponseStatus.Errors);
                return result;
            }

            result.success = true;
            result.msg = Defineds.DefaultSuccessMsg;
            return result;
        }

        /// <summary>
        /// 下推
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static Result Push(Context context, Parameter parameter)
        {
            Result result = new Result();
            var rs = WebApiServiceCall.Push(context, parameter.NextFormId, Formater.Push(parameter));
            ResponseData res = Formater.ConvertWebAPIResult(rs);
            if (!res.Result.ResponseStatus.IsSuccess)
            {
                result.msg = JsonConvert.SerializeObject(res.Result.ResponseStatus.Errors);
                return result;
            }

            JArray bills = new JArray();
            foreach (ResponseDataResultSuccessEntitys item in res.Result.ResponseStatus.SuccessEntitys)
            {
                JObject bill = new JObject
                {
                    new JProperty("FID", item.Id),
                    new JProperty("Number", item.Number)
                };
                bills.Add(bill);
            }

            result.data = new JObject { new JProperty("Bills", bills) };
            result.success = true;
            result.msg = Defineds.DefaultSuccessMsg;
            return result;
        }

        /// <summary>
        /// 下推、更新和审核
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static Result PushAndUpdate(Context context, Parameter parameter)
        {
            Result result = new Result();
            var rsPush = WebApiServiceCall.Push(context, parameter.NextFormId, Formater.Push(parameter));
            ResponseData res = Formater.ConvertWebAPIResult(rsPush);
            if (!res.Result.ResponseStatus.IsSuccess)
            {
                result.msg = JsonConvert.SerializeObject(res.Result.ResponseStatus.Errors);
                return result;
            }

            // 更新单据
            JArray entryIds = Utils.getSrcEntryIds(parameter);
            DynamicObjectCollection entryIdData = Utils.getEntryLinkID(context, parameter.NextFormId, parameter.NextQueryEntryKey, entryIds);
            var rsSave = WebApiServiceCall.Save(context, parameter.NextFormId, Formater.Update(parameter, entryIdData));
            ResponseData rsSaveData = Formater.ConvertWebAPIResult(rsSave);
            if (!rsSaveData.Result.ResponseStatus.IsSuccess)
            {
                result.msg = JsonConvert.SerializeObject(rsSaveData.Result.ResponseStatus.Errors) + Defineds.DefaultPushSaveErrorMsg;
                return result;
            }

            result.data = new JObject
            {
                new JProperty("FID", res.Result.ID),
                new JProperty("Number", res.Result.Number)
            };

            if (parameter.IsAutoSubmitAndAudit)
            {
                // 提交
                if (parameter.Model.Property("FID") == null && Convert.ToInt64(parameter.Model["FID"]) == 0)
                {
                    parameter.Model.Add(new JProperty("FID", res.Result.ID));
                }

                if (parameter.Model.Property("FBillNo") == null && Convert.ToInt64(parameter.Model["FBillNo"]) == 0)
                {
                    parameter.Model.Add(new JProperty("FBillNo", res.Result.Number));
                }

                var rsSubmit = WebApiServiceCall.Submit(context, parameter.NextFormId, Formater.Submit(parameter));
                ResponseData rsSubmitData = Formater.ConvertWebAPIResult(rsSubmit);
                if (!rsSubmitData.Result.ResponseStatus.IsSuccess)
                {
                    result.msg = JsonConvert.SerializeObject(rsSubmitData.Result.ResponseStatus.Errors) + Defineds.DefaultPushSaveErrorMsg;

                    // 删除提交失败的订单，重新下推
                    var rs = WebApiServiceCall.Delete(context, parameter.NextFormId, Formater.Delete(parameter));
                    ResponseData rsData = Formater.ConvertWebAPIResult(rs);
                    // 删除失败
                    if (!rsData.Result.ResponseStatus.IsSuccess)
                    {
                        result.msg += JsonConvert.SerializeObject(rsData.Result.ResponseStatus.Errors) + " 星空系统单据处理失败，请根据单据编号，人工手动处理。";
                        return result;
                    }

                    result.success = false;
                    return result;
                }

                // 审核
                var rsAudit = WebApiServiceCall.Audit(context, parameter.NextFormId, Formater.Audit(parameter));
                ResponseData rsAuditData = Formater.ConvertWebAPIResult(rsAudit);
                if (!rsAuditData.Result.ResponseStatus.IsSuccess)
                {
                    result.success = false;
                    result.msg = JsonConvert.SerializeObject(rsAuditData.Result.ResponseStatus.Errors) + " 星空系统单据处理失败，请根据单据编号，人工手动处理。";
                    return result;
                }
            }

            result.msg = Defineds.DefaultSuccessMsg;
            return result;
        }
    }
}
